package util;

import java.rmi.RMISecurityManager;
import java.rmi.Remote;
import java.rmi.registry.LocateRegistry;
import java.rmi.server.UnicastRemoteObject;


public class RmiService
{
	public static Remote createNewRmiServer(Class<?> RmiServerClass,Class<?> RmiInterface,final String bindName)
	{

		System.setProperty("java.rmi.server.codebase", RmiInterface
		 .getProtectionDomain().getCodeSource().getLocation().toString());
		System.out.println(System.getProperty("java.rmi.server.codebase"));
		System.setProperty("java.security.policy",
				PolicyFile.getLocationOfPolicyFile());

		if (System.getSecurityManager() == null)
		{
			
			System.setSecurityManager(new RMISecurityManager());
		}
		Remote stub = null;
		try
		{
			final Remote obj = (Remote) RmiServerClass.getConstructors()[0].newInstance();
			stub = (Remote) UnicastRemoteObject
					.exportObject(obj,0);
			LocateRegistry.getRegistry().bind(bindName, stub);
			Runtime.getRuntime().addShutdownHook(new Thread()
			{
				@Override
				public void run()
				{

					try
					{
						System.out.println("unexporting master");
						LocateRegistry.getRegistry().unbind(bindName);
						UnicastRemoteObject.unexportObject(obj, true);
					} catch (Exception e)
					{
						System.out.println("Exception " + e);
					}

					// LocateRegistry.getRegistry().unbind(arg0)
				}
			});
			System.out.println("hai server rdy");
		} catch (Exception e)
		{
			System.err.println("Exception " + e);
			e.printStackTrace();
		}
		return stub;
	}
}
